package com.example.nacosprovider.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class RedisUtils {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据key值查询value的所有键值对
     * @return
     */
    public List getUserList() {
        //查询key值
        Set<String> keys = stringRedisTemplate.keys("spring:session:index:org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME:*");
        List<String> userList = new LinkedList<>();
        log.info(keys.toString());
        for(String key : keys) {
            //替换掉前缀只留下用户名
            String users=key.replace("spring:session:index:org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME:", "");
            userList.add(users);
        }
        return userList;
    }

    public Boolean delSession(String userName) {
        String key = "spring:session:index:org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME:" + userName;
        System.out.println(key);
        return stringRedisTemplate.delete(key);
    }
}
